package com.example.schedule;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p> ScheduleConfig </p>
 *
 * @author Stranger.
 * @since 2022/5/25 17:18
 */
@Slf4j
@Component
@Configuration
@EnableScheduling
public class ScheduleConfig {
    @Value("${cross-network.authId}")
    private String crossAuthId;
    @Value("${cross-network.authPwd}")
    private String crossAuthPwd;
    @Value("${cross-network.url}")
    private String crossUrl;

    // 添加定时任务(每20分钟执行一次)
    @PostConstruct
    @Scheduled(cron = "0 0/20 * * * ?")
    private void configureTasks() {
        log.info("-----------开始定时任务-----------");
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("authId", crossAuthId);
            map.put("authPwd", crossAuthPwd);
            log.info("请求地址:"+crossUrl+"\n 请求参数:"+map.toString());
            String result = HttpUtil.post(crossUrl, map);
            // 发生错误，重试三次
            if (StrUtil.isNotBlank(result) && result.indexOf("error") != -1) {
                int times = 3;
                boolean errorFlag = true;
                while (times > 0) {
                    result = HttpUtil.post(crossUrl, map);
                    log.info("token-while-result->{}", result);
                    // 再次请求时，正常则结束循环
                    if (StrUtil.isNotBlank(result) && result.indexOf("error") == -1) {
                        errorFlag = false;
                        break;
                    }
                    times--;
                }
                if (errorFlag) {
                    log.error("重试三次获取token依旧失败--->{}", result);
                    return ;
                }
            }
            // 将token放入map
            log.info("result->{}",result);
            ScheduleConstants.TOKEN.put(ScheduleConstants.TOKEN_KEY, result);
            ScheduleConstants.TOKEN.put(ScheduleConstants.TOKEN_TIME, String.valueOf(System.currentTimeMillis()/1000));
        }catch (Exception e){
            log.error("获取认证token失败:{}",e.getMessage());
            e.printStackTrace();
        }
        log.info("-----------结束定时任务-----------");
    }
}
